<template>
  <view class="box">
    <!-- 提示验证码 -->
    <view class="title">
      报修房屋
    </view>

    <view class="box-cell">
      <u-cell-group :border='false'>
        <u-cell :border='false' :title="houseName" isLink @click="getHouse('请填写报修房屋')">
        </u-cell>
      </u-cell-group>
    </view>

    <view class="title">
      报修信息
    </view>


    <u-form>
      <u-form-item label="维修项目" labelWidth="208rpx" borderBottom @click='onrepairItem("请选择维修项目")'>
        <u--input border="none" placeholder="请选择" suffixIcon="arrow-right"
          suffixIconStyle="color: #999;font-size: 16px;" v-model="repairItem">
        </u--input>
      </u-form-item>
      <u-form-item label="手机号" labelWidth="208rpx" borderBottom>
        <u--input border="none" placeholder="请填写您的手机号" v-model="repair.mobile"></u--input>
      </u-form-item>
      <u-form-item label="预约时间" labelWidth="208rpx" borderBottom @click="show1 = true">
        <u--input border="none" placeholder="请选择上门维修时间" v-model="repair.appointment" suffixIcon="arrow-right"
          suffixIconStyle="color: #999;font-size: 16px;"></u--input>
      </u-form-item>
    </u-form>

    <view class="wenti">
      <u-cell-group :border='false'>
        <u-cell :border='false' title="问题描述">
        </u-cell>
        <u--textarea placeholder="请填写详细报修内容，有助于工作人员快速帮您解决问题。" border="none" v-model="repair.description"></u--textarea>
      </u-cell-group>
    </view>
    <!-- -->
    <view class="wenti">
      <u-cell-group :border='false'>
        <u-cell :border='false' title="问题附件">
        </u-cell>
        <u-upload :fileList="fileList3" @afterRead="afterRead" @delete="deletePic" name="3" multiple :maxCount="10"
          :previewFullImage="true"></u-upload>
      </u-cell-group>
    </view>
    <!-- 弹出 -->
    <view class="popup">
      <u-action-sheet round=10 :actions="list" :closeOnClickOverlay="true" :closeOnClickAction="true" :title="title"
        :show="show" @close='onClose' @select="selectClick" cancelText='取消'>
      </u-action-sheet>
    </view>
    <!-- 日期弹出 -->
    <u-datetime-picker :round="10" ref="datetimePicker" closeOnClickOverlay title='选择上门日期' :minDate="value1"
      :show="show1" v-model="value1" mode="date" :formatter="formatter" @close="onClose" @confirm='onConfirm'
      @cancel="show1=false">
    </u-datetime-picker>



    <life-button icon='../../static/icon/repair.png' @click="addRepair">提交报修</life-button>
  </view>
</template>

<script>
  import {
    getHouse,
    getRepairItem,
    postRepair,
    getRepairDetail
  } from "@/api/repair.js"
  import {
    getTime
  } from "@/utils/time.js"
  import toast from "@/utils/toast.js"
  export default {
    data() {
      return {
        fileList3: [],
        // 弹出
        list: [],
        show: false,
        title: '',
        // 发请求数据
        repair: {
          houseId: null,
          repairItemId: null,
          mobile: null,
          appointment: null,
          description: null,
          attachment: []
        },
        // 房屋内容
        houseName: "请填写报修房屋",
        // 维修内容
        repairItem: '',
        // 日期弹出开关
        show1: false,
        // 日期数据
        value1: Number(new Date()),
      }
    },
    onReady() {
      // 微信小程序需要用此写法
      this.$refs.datetimePicker.setFormatter(this.formatter)
    },
    async onLoad({
      id
    }) {
      // console.log(id)
      if (!id) return
      this.id = id
      uni.setNavigationBarTitle({
        title: "修改报修信息"
      })
      const res = await getRepairDetail(id)
      // console.log(res.data)
      this.repair = res.data
      this.houseName = res.data.houseInfo
      this.repairItem = res.data.repairItemName
      delete this.repair.houseInfo
      delete this.repair.repairItemName
      this.fileList3 = res.data.attachment.map(item => {
        return {
          id: item.id,
          thumb: item.url,
          type: 'image'
        }
      })
    },
    methods: {
      // 日期事件
      formatter(type, value) {
        if (type === 'year') {
          return `${value}年`
        }
        if (type === 'month') {
          return `${value}月`
        }
        if (type === 'day') {
          return `${value}日`
        }
        return value
      },
      // 时间选择器确定
      onConfirm(value) {
        this.repair.appointment = getTime(value.value)
        this.show1 = false
      },
      // 点击房屋
      async getHouse(e) {
        this.title = e
        this.show = true
        const res = await getHouse()
        if (res.data.length) {
          this.list = res.data
        } else {
          this.list = [{
            name: '无数据',
            disabled: true
          }, ]
        }
      },
      // 点击维修
      async onrepairItem(e) {
        this.title = e
        this.show = true
        const res = await getRepairItem()
        this.list = res.data
      },
      // 关闭弹出
      onClose() {
        this.show = false
        this.show1 = false
      },
      // 点击选项
      selectClick(index) {
        if (this.title === '请填写报修房屋') {
          this.repair.houseId = index.id
          this.houseName = index.name

        } else {
          this.repair.repairItemId = index.id
          this.repairItem = index.name
        }
        this.show = false
      },
      // 点击提交报修
      async addRepair() {

        // 电话正则
        const mobile = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
        if (!this.repair.houseId) return toast('请选择房屋信息')
        if (!this.repair.repairItemId) return toast('请选择维修项目')
        if (!mobile.test(this.repair.mobile)) return toast('请输入有效号码')
        if (!this.repair.appointment) return toast('请选择预约日期')
        if (!this.repair.description) return toast('请填写问题描述')
        if (!this.repair.attachment.length) return toast('请上传问题附件')
        const res = await postRepair(this.repair)
        uni.navigateTo({
          url: "/pkg-repair/repair/repair"
        })
      },
      // ----------------------------------------------------------
      // 删除图片
      deletePic(event) {
        this.repair.attachment.splice(event.index, 1)
        this[`fileList${event.name}`].splice(event.index, 1)
        // console.log(this.fileList3, event.index)
      },
      // 新增图片
      async afterRead(event) {
        // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
        // console.log(event)
        let lists = [].concat(event.file)
        let fileListLen = this[`fileList${event.name}`].length
        lists.map((item) => {
          this[`fileList${event.name}`].push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url)
          let item = this[`fileList${event.name}`][fileListLen]
          this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
            status: 'success',
            message: '',
            url: result
          }))
          fileListLen++
        }
        // console.log(this.fileList3, 1)
      },
      uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: 'https://live-api.itheima.net/upload',
            filePath: url,
            name: 'file',
            header: {
              Authorization: 'Bearer ' + this.$store.state.user.userToken.token
            },
            success: (res) => {
              this.repair.attachment.push(JSON.parse(res.data).data)
              setTimeout(() => {
                resolve(res.data.data)
              }, 1000)
            }
          });
        })
      },
    }

  }
</script>

<style scoped lang="scss">
  .box {
    height: 100%;
    background-color: #FAFAFA;
    padding-bottom: 650rpx;

    .title {
      padding: 0 30rpx;
      line-height: 86rpx;
      color: #979797;
      font-size: 24rpx;
    }

    ::v-deep .u-cell__body {
      background: #ffffff;
      height: 102rpx;
      // padding: 0;
      // margin: 0 15px;
      border-bottom: 1px solid #FAFAFA;
    }

    ::v-deep .u-form-item__body {
      background: #fff;
      height: 102rpx;
      padding: 30rpx;
      box-sizing: border-box;
    }

    .wenti {
      border-bottom: 1px solid #e9eaeb;

      ::v-deep .u-cell__body {
        background: #ffffff;
        height: 92rpx;
        // padding: 0;
        // margin: 0 15px;
        border-bottom: unset;
      }

      ::v-deep textarea {
        height: 114rpx !important;
      }

      ::v-deep .u-textarea {
        padding: 30rpx;
        padding-top: unset;
        padding-bottom: unset;
      }

      // 上传
      ::v-deep .u-upload {
        background: #fff;
        padding: 0 30rpx;
      }
    }

    .popup {
      ::v-deep .u-icon__icon {
        display: none;
      }
    }

    ::v-deep .u-transition {
      .u-popup__content {
        border-radius: 10px;
      }

      .u-toolbar__wrapper__confirm {
        color: #6199b5 !important;
      }
    }
  }
</style>
